<template>
  <el-card>
    <el-row style="margin-top: 20px;">
      <el-col :span="14" :offset="4">
        <!-- 选择食品种类 -->
        <header class="form_header">选择食品种类</header>
        <el-card shadow="hover">
          <el-form ref="goodsFormRef" :model="categoryForm" label-width="80px">
            <!-- 食品分类 -->
            <el-form-item label="食品分类">
              <el-select v-model="categoryForm.categorySelect" placeholder="请选择分类">
                <el-option v-for="item in categoryForm.categoryList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="text-align:center;">
              <el-button type="primary" size="mini" @click="dialogVisible = true">添加食品分类</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 添加食品 -->
      <el-col :span="14" :offset="4">
        <!-- 选择食品种类 -->
        <header class="foot_header">添加食品</header>
        <el-card shadow="hover">
          <el-form ref="foodFormRef" :model="foodForm" :rules="foodFormRules" label-width="80px">
            <!-- 食品分类 -->
            <el-form-item label="食品名称" prop="name">
              <el-input v-model="foodForm.name"></el-input>
            </el-form-item>
            <el-form-item label="食品活动">
              <el-input v-model="foodForm.activity"></el-input>
            </el-form-item>
            <el-form-item label="食品详情">
              <el-input v-model="foodForm.description"></el-input>
            </el-form-item>
            <!-- 上传图片 -->
            <el-form-item label="上传食品图片">
              <el-upload class="avatar-uploader" :action="baseURL + '/v1/addimg/food'" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="foodForm.image_path" :src="baseImgPath + foodForm.image_path" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="食品特点">
              <el-select v-model="foodForm.attributes" multiple placeholder="请选择">
                <el-option v-for="item in attributes" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>

            <!-- 食品规格 -->
            <el-form-item label="食品规格">
              <el-radio v-model="foodSpecs" label="one">单规格</el-radio>
              <el-radio v-model="foodSpecs" label="more">多规格</el-radio>
            </el-form-item>

            <!-- 价格 -->
            <el-row v-if="foodSpecs === 'one'">
              <el-form-item label="包装费">
                <el-input-number v-model="foodForm.specs[0].packing_fee" :min="0" :max="100"></el-input-number>
              </el-form-item>
              <el-form-item label="价格">
                <el-input-number v-model="foodForm.specs[0].price" :min="0" :max="10000"></el-input-number>
              </el-form-item>
            </el-row>

            <!-- 多规格 -->
            <el-row v-if="foodSpecs === 'more'" style="overflow: auto; text-align: center;">
              <el-button type="primary" @click="dialogFormVisible = true" style="margin-bottom:20px">添加规格</el-button>
              <el-table :data="foodForm.specs" style="width: 100%">
                <el-table-column prop="specs" label="规格"> </el-table-column>
                <el-table-column prop="packing_fee" label="姓名"> </el-table-column>
                <el-table-column prop="price" label="价格"> </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="danger" size="mini" @click="deleteSpecsID(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="addFood">确认添加食品</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 点击食品分类弹出框 -->
    <el-dialog title="添加食品种类" :visible.sync="dialogVisible" width="50%">
      <el-form ref="categoryItemRef" :model="categoryForm">
        <el-form-item label="食品分类">
          <el-input v-model="categoryForm.name"></el-input>
        </el-form-item>
        <el-form-item label="种类描述">
          <el-input v-model="categoryForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="subitmCategory(categoryForm)">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加规格" :visible.sync="dialogFormVisible" width="50%">
      <el-form ref="specsFormRef" :model="specsForm">
        <el-form-item label="规格">
          <el-input v-model.trim="specsForm.specs"></el-input>
        </el-form-item>
        <el-form-item label="包装费">
          <el-input-number v-model="specsForm.packing_fee" :min="0" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="specsForm.price" :min="0" :max="10000"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSpecs">确认添加食品</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
// import request from '../api/axiosApi'
import { baseURL, baseImgPath } from '../api/env'
import { getCategory, addCategory, addFood } from '../api/index'
export default {
  data() {
    return {
      dialogVisible: false,
      dialogFormVisible: false,
      baseURL,
      baseImgPath,
      categoryForm: {
        name: '',
        description: '',
        categoryList: [],
        categorySelect: ''
      },
      restaurant_id: 1,
      foodForm: {
        name: '',
        activity: '',
        description: '',
        image_path: '',
        attributes: '',
        specs: [
          {
            specs: '默认',
            packing_fee: 0,
            price: 20
          }
        ]
      },
      attributes: [
        { value: '新品', label: '新品' },
        { value: '招牌', label: '招牌' }
      ],
      foodFormRules: {
        name: [{ required: true, message: '请输入食品名称', trigger: 'blur' }]
      },
      foodSpecs: 'one',
      specsForm: {
        specs: '',
        packing_fee: 0,
        price: 20
      }
    }
  },
  created() {
    if (this.$route.query.restaurant_id) {
      this.restaurant_id = this.$route.query.restaurant_id
    } else {
      this.restaurant_id = Math.ceil(Math.random() * 10)
      this.$msgbox({
        title: '提示',
        message: '添加食品需要选择一个商铺,先去就去选择商铺码？',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            this.$router.push('/shoplist')
            done()
          } else {
            this.$message.info('取消')
          }
          done()
        }
      })
    }
    this.initData()
  },
  methods: {
    async initData() {
      try {
        const { data: res } = await getCategory(this.restaurant_id)
        if (res.status === 1) {
          res.category_list.map((item, index) => {
            item.value = index
            item.label = item.name
          })
          this.categoryForm.categoryList = res.category_list
        } else {
          console.log(res)
        }
      } catch (error) {
        console.log(error)
      }
    },
    subitmCategory(refs) {
      this.$refs.categoryItemRef.validate(async valid => {
        if (valid) {
          const params = {
            name: refs.name,
            description: refs.description,
            restaurant_id: this.restaurant_id
          }
          try {
            const { data: result } = await addCategory(params)
            this.dialogVisible = false
            if (result.status === 1) {
              this.initData()
              this.categoryForm.name = ''
              this.categoryForm.description = ''
              this.$message.success('添加成功')
            } else {
              this.$message.error(result.message)
            }
          } catch (error) {
            console.log(error)
          }
        } else {
          console.log('不行')
        }
      })
    },
    handleAvatarSuccess(file) {
      if (file.status === 1) {
        this.foodForm.image_path = file.image_path
      } else {
        this.$message.error('上传图片失败')
      }
    },
    beforeAvatarUpload(file) {
      const isRightPath = file.type === 'image/jpeg' || file.type === 'image/png'
      const isSize2M = file.size / 1024 / 1024 < 2
      if (!isRightPath) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isSize2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isRightPath && isSize2M
    },
    addSpecs() {
      this.$refs.specsFormRef.validate(valid => {
        if (valid) {
          if (this.specsForm.specs) {
            this.foodForm.specs.push(this.specsForm)
            this.specsForm = {
              specs: '',
              packing_fee: 0,
              price: 20
            }
            this.dialogFormVisible = false
          } else {
            this.$message.error('请输入规格')
          }
        } else {
          console.log('ok')
        }
      })
    },
    deleteSpecsID(index) {
      this.foodForm.specs.splice(index, 1)
    },
    addFood() {
      this.$refs.foodFormRef.validate(async valid => {
        if (valid) {
          const params = {
            ...this.foodForm,
            // category_id:this.selectValue.id
            restaurant_id: this.restaurant_id
          }
          try {
            const { data: result } = await addFood(params)
            if (result.status === 1) {
              this.$message.success('添加成功')
              this.foodForm = {
                name: '',
                activity: '',
                description: '',
                image_path: '',
                attributes: '',
                specs: [
                  {
                    specs: '默认',
                    packing_fee: 0,
                    price: 20
                  }
                ]
              }
            } else {
              this.$message.error(result.message)
            }
          } catch (error) {
            console.log(error)
          }
        } else {
          this.$notify.error({
            title: '错误',
            message: '请检查输入是否正确',
            offset: 100
          })
          return false
        }
      })
    }
  }
}
</script>
<style lang="less">
.form_header {
  text-align: center;
  margin-bottom: 20px;
}
.foot_header {
  margin: 40px 0 20px 0;
  text-align: center;
}
</style>
